/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package taskmanager2ndedition.client;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import taskmanager2ndedition.ClientUserInfo;

/**
 *
 * @author denaas
 */
public class ClientUserManager {    
    private List<ClientUserInfo> list = new LinkedList<ClientUserInfo>();
    private ClientController controller;
    private Timer timer;
    
    private class UpdateUserList extends TimerTask{

        @Override
        public void run() {
            List<ClientUserInfo> updateList = controller.updateUsers();
            if (updateList == null || updateList.isEmpty())
                return;
            for(ClientUserInfo user: updateList){
                switch(user.getState()){
                    case Added:
                        if (findById(user.getId()) == null){
                            add(user);
                        }
                        break;
                    case Removed:
                        remove(user);
                        break;
                }
            }
            controller.setUserListModified(true);
        }
        
    }
    
    public ClientUserManager(ClientController controller){
        this.controller = controller;        
        forceUpdate();
        
        
        timer = new java.util.Timer();
        timer.scheduleAtFixedRate(new UpdateUserList(), new Date(), controller.getUpdatePeriod());
    }

    public void remove(ClientUserInfo user) {
        if (user == null)
            return;
        ClientUserInfo userToRemove = findById(user.getId());
        list.remove(userToRemove);
    }
    
    public void add(ClientUserInfo user) {
        if (user == null)
            return;
        list.add(user);
    }
    
    public ClientUserInfo findById(int id) {
        for (ClientUserInfo user: list){
            if (user.getId() == id)
                return user;
        }
        
        return null;
    }

    public List<ClientUserInfo> getUsers() {
        return list;
    }    
    
    public void forceUpdate() {
        list.clear();
        controller.setUserListModified(true);
        List<ClientUserInfo> updateList = controller.getAllUsers();
        if (updateList == null || updateList.isEmpty())
            return;
        for(ClientUserInfo user: updateList){
            switch(user.getState()){
                case Added:
                    if (findById(user.getId()) == null){
                            add(user);
                    }
                    break;
                case Removed:
                    remove(user);
                    break;
            }
        }        
    }    
    
    public void finalize(){
        timer.cancel();
    }
}
